<template>
	<!-- 播放器 -->
  <div class="player" v-show="playlist.length>0"  id="pk">
	<!-- 播放器 -->
   <transition name="normal"
    @enter="enter"
    @after-enter="afterEnter"
    @leave="leave"
    @after-leave="afterLeave"
   >
    <div class="normal-player" v-show="fullScreen">
			<!-- img -->
        <div class="background" v-show="currentSong.pic" >
          <img width="100%" height="100%" :src="currentSong.pic" >
        </div>
				<!-- btn -->
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
					<h3 class="sunhun" v-if="mv" @click="btnmv"><router-link :to="mv">查看<br>MV</router-link></h3>
        </div>
				<!-- 唱片机 3个滑动事件-->
        <div class="middle"
             @touchstart.prevent="middleTouchStart"
             @touchmove.prevent="middleTouchMove"
             @touchend="middleTouchEnd"
        >
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper">
							<!-- 不停运动的小圆盘 -->
              <div class="cd" :class="cdCls">
                <img class="image" :src="currentSong.pic">
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
					<!-- 歌词的界面 -->
          <scroll class="middle-r" ref="lyricList" :dataA="currentLyric && currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p ref="lyricLine"
                   class="text"
                   :class="{'current': currentLineNum ===index}"
                   v-for="(line,index) in currentLyric.lines">{{line.txt}}</p>
              </div>
            </div>
          </scroll>
       
				</div>
				<!-- 底部操作区 -->
        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{'active':currentShow==='cd'}"></span>
            <span class="dot" :class="{'active':currentShow==='lyric'}"></span>
          </div>
          <div class="progress-wrapper">
						<!-- 歌曲播放当前时间 -->
            <span class="time time-l">{{format(currentTime)}}</span>
            <div class="progress-bar-wrapper">
							<!-- 音乐播发时间线条组件 -->
              <progress-bar :percent="percent" 
							    @percentChange="onProgressBarChange">
							</progress-bar>
            </div>
						<!-- 歌曲播放总时间 -->
            <span class="time time-r">{{format(currentSong.time)}}</span>
          </div>
          <div class="operators">
						<!-- 播放模式 -->
						<div class="icon i-left" @click="changeMode">
						  <i :class="iconMode"></i>
						</div>
						<div class="icon i-left" :class="disableCls">
						  <i @click="prev" class="icon-prev"></i>
						</div>
						<!-- 播放或暂停 -->
						<div class="icon i-center" :class="disableCls">
							<i @click="togglePlaying" :class="playIcon"></i>
						</div>
						<div class="icon i-right" :class="disableCls">
						  <i @click="next" class="icon-next"></i>
						</div>
						<!-- 收藏 -->
						<div class="icon i-right">
						  <i @click="toggleFavorite(currentSong)" class="icon" :class="getFavoriteIcon(currentSong)"></i>
						</div>
          </div>
        </div>

			</div>
   </transition>
		<!-- 底部迷里播放器 -->
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="open">
       <!-- 不停运动的小圆盘 -->
			 <div class="icon">
          <img :class="cdCls" width="40" height="40" :src="currentSong.pic">
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"></h2>
          <p class="desc" v-html="currentSong.singer"></p>
        </div>
				<!-- 播放或暂停 -->
        <div class="control">
					<!-- 迷里小园圈播放器组件 -->
         <progress-circle :radius="radius" :percent="percent">
            <i @click.stop="togglePlaying" class="icon-mini" :class="miniIcon"></i>
          </progress-circle>
        </div>
				<!-- 点击图标显示playlist列表 -->
        <div class="control" @click.stop="showPlaylist">
          <i class="icon-playlist"></i>
        </div>
      </div>
		</transition>
		
    <playlist ref="playlist"></playlist>
   <!-- ready w3c 歌曲准备就绪 timeupdate 歌曲播放派发时间 error 发生错误 -->
		<audio
		  id="music_mp3_0"
			ref="audio" 
			:src="currentSong.url" 
			@play="ready" 
			@error="error" 
			@timeupdate="updateTime"
      @ended="end">
		</audio> 
  </div>
</template>

<script >
  import {mapGetters, mapMutations, mapActions} from 'vuex'
  import animations from 'create-keyframe-animation'
  import {prefixStyle} from 'common/js/dom'
  import ProgressBar from 'base/progress-bar/progress-bar'
  import ProgressCircle from 'base/progress-circle/progress-circle'
  import {playMode} from 'common/js/config'
	import {ERR_OK,ERR_GO} from 'api/config'
   import Lyric from 'lyric-parser' //没有请求链接
  import Scroll from 'base/scroll/scroll'
  import {playerMixin,playpop} from 'common/js/mixin'
	import {shuffle} from 'common/js/util.js'
  import Playlist from 'components/playlist/playlist'
  import axios from 'axios'
   const transform = prefixStyle('transform')
   const transitionDuration = prefixStyle('transitionDuration')

  export default {
    mixins: [playerMixin,playpop],
		name: 'player',
    data() {
      return {
        songReady: false,//歌曲准备就绪
        currentTime: 0,
        radius: 32,
        currentLyric: null,//歌词
        currentLineNum: 0,//歌词高亮行数
        currentShow: 'cd',//歌词页面滑动参数
        playingLyric: '',
				mv:"",
				sosmv:""
      }
    },
    computed: {
      cdCls() {//不停运动的小圆盘
        return this.playing ? 'play' : 'play pause'
      },
      playIcon() {//播放或暂停的图标
        return this.playing ? 'icon-pause' : 'icon-play'
      },
      miniIcon() {//播放或暂停的图标
        return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
      },
      disableCls() { //播放禁止
        return this.songReady ? '' : 'disable'
      },
      percent() {//动态计算小球的运动百分比
        return this.currentTime / this.currentSong.time
      },
      ...mapGetters([
        'currentIndex',
        'fullScreen',
				'playlist',
        'playing',
				'currentSong',
				'mode',
				'sequenceList',
				// 'gedata',
				'istrue',
      ])
    },
    created() {
      this.touch = {}
    },
		mounted(){},
    methods: {
      back() { //回退建 张开或收起播放器
			  const audio = this.$refs.audio
			  this.playing ? audio.play() : audio.pause()
        this.setFullScreen(false)
      },
      open() {
				const audio = this.$refs.audio
				this.playing ? audio.play() : audio.pause()
        this.setFullScreen(true)
      },
      enter(el, done) {
        const {x, y, scale} = this._getPosAndScale()

        let animation = {
          0: {
            transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
          },
          60: {
            transform: `translate3d(0,0,0) scale(1.1)`
          },
          100: {
            transform: `translate3d(0,0,0) scale(1)`
          }
        }

        animations.registerAnimation({//动画配置 
          name: 'move',
          animation,
          presets: {
            duration: 400,
            easing: 'linear'
          }
        })
         //动画引用
        animations.runAnimation(this.$refs.cdWrapper, 'move', done)
      },
      afterEnter() {
        animations.unregisterAnimation('move')
        this.$refs.cdWrapper.style.animation = ''
      },
      leave(el, done) {
        this.$refs.cdWrapper.style.transition = 'all 0.4s'
        const {x, y, scale} = this._getPosAndScale()
        this.$refs.cdWrapper.style[transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
        this.$refs.cdWrapper.addEventListener('transitionend', done)
      },
      afterLeave() {
        this.$refs.cdWrapper.style.transition = ''
        this.$refs.cdWrapper.style[transform] = ''
      },
      togglePlaying() {//底部迷你播放或暂停
				//console.log("!this.playing",!this.playing)
        if (!this.songReady) {
          return
        }
        this.setPlayingState(!this.playing)//暂停
			
        if (this.currentLyric) {
          this.currentLyric.togglePlay()
        }
      },
      end() { //切换到下一首
        if (this.mode === playMode.loop) {
          this.loop()
        } else {
          this.next()
        }
      },
      loop() {//循环播发的功能
        this.$refs.audio.currentTime = 0
				//--创建触摸监听，当浏览器打开页面时，触摸屏幕触发事件，进行音频播放
				let that =this
// 			 document.addEventListener('touchstart', function () {
// 				function audioAutoPlay() {
// 						let musicEle0 = document.getElementById('music_mp3_0');
// 						    that.playing ? musicEle0.play() : musicEle0.pause()
// 				}
// 				audioAutoPlay();
// 			});
        this.$refs.audio.play()
        this.setPlayingState(true)
        if (this.currentLyric) {
          this.currentLyric.seek(0)
        }
      },
      next() {//下一首歌曲
        if (!this.songReady) {
          return
        }
        if (this.playlist.length === 1) {//如果只有一条信息
          this.loop()
          return
        } else {
          let index = this.currentIndex + 1
          if (index === this.playlist.length) {
            index = 0
          }
          this.setCurrentIndex(index)
					this.QieHuan(this.currentIndex)// 排行榜数据切换下一页的方法
          if (!this.playing) {
            this.togglePlaying() //底部迷你播放或暂停
          }
        }
        this.songReady = false
      },
      prev() {//上一首歌曲
        if (!this.songReady) {
          return
        }
        if (this.playlist.length === 1) {
          this.loop()
          return
        } else {
          let index = this.currentIndex - 1
          if (index === -1) {
            index = this.playlist.length - 1
          }
          this.setCurrentIndex(index)
					this.QieHuan(this.currentIndex)// 排行榜数据切换下一页的方法
          if (!this.playing) {
            this.togglePlaying()
          }
        }
        this.songReady = false
      },
      ready() {//歌曲准备就绪 写入历史数据
        this.songReady = true
				this.savePlayHistory(this.currentSong)
				// console.log('setCurrentIndex',this.currentIndex)
      },
      error() {//歌曲错误信息
        this.songReady = true
      },
      updateTime(e) { //歌曲播放派发时间
        this.currentTime = e.target.currentTime
      },
      format(interval) { //秒的时间戳转化
        interval = interval | 0
        const minute = interval / 60 | 0
        const second = this._pad(interval % 60)
        return `${minute}:${second}`
      },
      onProgressBarChange(percent) {// duration总时长 实时更新小球时间 progress-bar
        const currentTime = this.currentSong.time * percent
        this.$refs.audio.currentTime = currentTime
        if (!this.playing) {
          this.togglePlaying()
        }
        if (this.currentLyric) {
          this.currentLyric.seek(currentTime * 1000)
        }
      },
      getLyric() {//自定义获取歌词 
			  let lrcy=this.currentSong.lrc;
				console.log("this.currentSong.lrc")
				if(lrcy){
					axios.get(lrcy)
					.then((lyric)=> {
						if (lyric.status === ERR_GO) {
								console.log('lyric.data',lyric)
								this.currentLyric = new Lyric(lyric.data,this.handleLyric)
								 if (this.playing) { //歌词判断
										this.currentLyric.play()
								 }
								// console.log('this.currentLyric',this.currentLyric)
							}
					}).catch(()=>{
						console.log("ppp")
						this.currentLyric=null
						this.playingLyric=''
						this.currentLineNum=0
					})
				}
		 },
      handleLyric({lineNum, txt}) {//歌词的回调函数
        this.currentLineNum = lineNum
        if (lineNum > 5) {
          let lineEl = this.$refs.lyricLine[lineNum - 5]
          this.$refs.lyricList.scrollToElement(lineEl, 1000)
        } else {
          this.$refs.lyricList.scrollTo(0, 0, 1000)
        }
        this.playingLyric = txt
      },
      showPlaylist() {//切换playlistt添加歌曲列表
        this.$refs.playlist.show()
      },
      middleTouchStart(e) { //滑动跳转页面
        this.touch.initiated = true
        // 用来判断是否是一次移动
        this.touch.moved = false
        const touch = e.touches[0]
        this.touch.startX = touch.pageX
        this.touch.startY = touch.pageY
      },
      middleTouchMove(e) {
        if (!this.touch.initiated) {
          return
        }
        const touch = e.touches[0]
        const deltaX = touch.pageX - this.touch.startX
        const deltaY = touch.pageY - this.touch.startY
        if (Math.abs(deltaY) > Math.abs(deltaX)) {
          return //如果y纵轴的距离大于x横轴的距离
					       //则取消滑动
        }
        if (!this.touch.moved) {
          this.touch.moved = true
        }
        const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
        const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
        this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
        this.$refs.lyricList.$el.style[transitionDuration] = 0
        this.$refs.middleL.style.opacity = 1 - this.touch.percent
        this.$refs.middleL.style[transitionDuration] = 0
      },
      middleTouchEnd() {
        if (!this.touch.moved) {
          return
        }
        let offsetWidth
        let opacity//右向左滑
        if (this.currentShow === 'cd') {
          if (this.touch.percent > 0.1) {
            offsetWidth = -window.innerWidth
            opacity = 0
            this.currentShow = 'lyric'
          } else {
            offsetWidth = 0
            opacity = 1
          }
        } else {//左向右滑
          if (this.touch.percent < 0.9) {
            offsetWidth = 0
            this.currentShow = 'cd'
            opacity = 1
          } else {
            offsetWidth = -window.innerWidth
            opacity = 0
          }
        }
        const time = 300
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
        this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`
        this.$refs.middleL.style.opacity = opacity
        this.$refs.middleL.style[transitionDuration] = `${time}ms`
        this.touch.initiated = false
      },
// 			changeMode(){//点击播放模式 2019 01 10
// 				const mode=(this.mode+1)%3
// 				this.setPlayMode(mode)
// 				let list =null;
// 				if(mode==playMode.random){ //2
// 			  	list=shuffle(this.sequenceList) //洗牌函数
// 				}else{
// 					list=this.sequenceList
// 				}
// 				this.resetCurrentIndex(list)
// 				this.setPlaylist(list)
// 			},
// 			resetCurrentIndex(list){//洗牌函数
// 				let index=list.findIndex((item)=>{
// 					return item.id==this.currentSong.id
// 				})
// 				this.setCurrentIndex(index)
// 			},
      _pad(num, n = 2) {//秒的扑0 00：59
        let len = num.toString().length
        while (len < n) {
          num = '0' + num
          len++
        }
        return num
      },
      _getPosAndScale() {//定义动画的简单函数
        const targetWidth = 40
        const paddingLeft = 40
        const paddingBottom = 30
        const paddingTop = 80
        const width = window.innerWidth * 0.8
        const scale = targetWidth / width
        const x = -(window.innerWidth / 2 - paddingLeft)
        const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
        return {
          x,
          y,
          scale
        }
      },
			//请求歌曲函数
			GeId(){
				if(this.currentSong.mid){
					 let currentSongID=this.currentSong.mid
					let url='https://api.bzqll.com/music/tencent/song?key=579621905&id='+currentSongID
					axios.get(url).then((res)=>{
						if(res.status==200){
							this.GOUB(res.data.data)
							console.log("resdd",res.data.data)
						}	
					}).catch(function(reason) {
							console.log('catch:',"请求歌曲函数出错" );
					});
				}
			},
			//获取视频的MV地址
			isMV(){
          if(!this.currentSong.id){return}
				  let currentSongID=this.currentSong.id
					let url=`https://api.bzqll.com/music/tencent/song?key=579621905&id=${currentSongID}&isOrigin=1`
					axios.get(url).then((res)=>{
						let mvt=res.data.data[0].mv.vid;
						this.sosmv=mvt
						mvt?(this.mv=`https://api.bzqll.com/music/tencent/mvUrl?key=579621905&id=${mvt}&r=4`):(this.mv="")
					  console.log(" res.data.data[0].mv.vid",this.mv)
			  }).catch(function(reason) {
						console.log('catch:',"获取视频的MV地址c出错" );
				});
			},
			btnmv(){ //点击查看MV
			this.back()
			 this.$router.push({
			  path: `/ismv/${this.sosmv}`
			})
				 console.log("dianj",this.sosmv)
			},
      ...mapMutations({
        setFullScreen: 'SET_FULL_SCREEN',
        setPlayingState:'SET_PLAYING_STATE',
				setCurrentIndex:'SET_CURRENT_INDEX',
				setPlayMode:'SET_PLAY_MODE',
				setPlaylist:'SET_PLAYLIST' ,
				GOUB:'GQUB', //歌曲信息
				QieHuan:'QieHuan',//切换歌曲信息currentSong
				
      }),
      ...mapActions([
        'savePlayHistory'
      ])
    },
    watch: {
      currentSong(newSong, oldSong) {//实时获取播放状态
			 if (!newSong||!newSong.id) {
			  return
			}
			if (newSong.id === oldSong.id) {
			  return
			}
       if(this.istrue){  //
          this.GeId()
				  this.isMV()
// 				  this.$nextTick(() => {
// 	 			   this.GeId()
// 				 })
				//   setTimeout(() => {
				//    this.GeId()
				// 	 this.isMV()
				//  },10)
			 }
	     // this.getLyric()
       
        
        if (this.currentLyric) {
          this.currentLyric.stop()
          this.currentTime = 0
          this.playingLyric = ''
          this.currentLineNum = 0
        }
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
					this.$refs.audio.play()
          this.getLyric() //获取歌词
        }, 1000)
      },
      playing(newPlaying) { //获取播放器的状态
        const audio = this.$refs.audio
        this.$nextTick(() => {
          newPlaying ? audio.play() : audio.pause()
        })
      },
      fullScreen(newVal) {
        if (newVal) {
          setTimeout(() => {
            this.$refs.lyricList.refresh()
          }, 20)
        }
      }
    },
		components: {
      ProgressBar,
      ProgressCircle,
      Scroll,
      Playlist
    }
  }
</script>

<style>
	.sunhun{    
		position: absolute;
    top: 5px;
    right: 12px;
    z-index: 50;
    height: 40px;
		display: flex;
    
	}
	.sunhun div{
		text-align: center;
		text-overflow: ellipsis;
		overflow: hidden;
		line-height: 12px;
	  justify-content: center;
		align-items: center;
		white-space: nowrap;
		font-size: 10px;
		padding-top: 4px;
		margin-top: 3px;
		width: 30px;
		height: 25px;
		color: #fff;
		border-radius:50%;
		border: 1px solid rgba(255,255,255,0.5);
	}
</style>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .player
    .normal-player
      position: fixed
      left: 0
      right: 0
      top: 0
      bottom: 0
      z-index: 150
      background: $color-background
      .background
        position: absolute
        left: 0
        top: 0
        width: 100%
        height: 100%
        z-index: -1
        opacity: 0.6
        filter: blur(20px)
      .top
        position: relative
        margin-bottom: 25px
        .back
          position absolute
          top: 0
          left: 6px
          z-index: 50
          .icon-back
            display: block
            padding: 9px
            font-size: $font-size-large-x
            color: $color-theme
            transform: rotate(-90deg)
        .title
          width: 70%
          margin: 0 auto
          line-height: 40px
          text-align: center
          no-wrap()
          font-size: $font-size-large
          color: $color-text
        .subtitle
          line-height: 20px
          text-align: center
          font-size: $font-size-medium
          color: $color-text
      .middle
        position: fixed
        width: 100%
        top: 80px
        bottom: 170px
        white-space: nowrap
        font-size: 0
        .middle-l
          display: inline-block
          vertical-align: top
          position: relative
          width: 100%
          height: 0
          padding-top: 80%
          .cd-wrapper
            position: absolute
            left: 10%
            top: 0
            width: 80%
            height: 100%
            .cd
              width: 100%
              height: 100%
              box-sizing: border-box
              border: 10px solid rgba(255, 255, 255, 0.1)
              border-radius: 50%
              &.play
                animation: rotate 20s linear infinite
              &.pause
                animation-play-state: paused
              .image
                position: absolute
                left: 0
                top: 0
                width: 100%
                height: 100%
                border-radius: 50%

          .playing-lyric-wrapper
            width: 80%
            margin: 30px auto 0 auto
            overflow: hidden
            text-align: center
            .playing-lyric
              height: 20px
              line-height: 20px
              font-size: $font-size-medium
              color: $color-text-l
        .middle-r
          display: inline-block
          vertical-align: top
          width: 100%
          height: 100%
          overflow: hidden
          .lyric-wrapper
            width: 80%
            margin: 0 auto
            overflow: hidden
            text-align: center
            .text
              line-height: 32px
              color: $color-text-l
              font-size: $font-size-medium
              &.current
                color: $color-text
      .bottom
        position: absolute
        bottom: 50px
        width: 100%
        .dot-wrapper
          text-align: center
          font-size: 0
          .dot
            display: inline-block
            vertical-align: middle
            margin: 0 4px
            width: 8px
            height: 8px
            border-radius: 50%
            background: $color-text-l
            &.active
              width: 20px
              border-radius: 5px
              background: $color-text-ll
        .progress-wrapper
          display: flex
          align-items: center
          width: 80%
          margin: 0px auto
          padding: 10px 0
          .time
            color: $color-text
            font-size: $font-size-small
            flex: 0 0 30px
            line-height: 30px
            width: 30px
            &.time-l
              text-align: left
            &.time-r
              text-align: right
          .progress-bar-wrapper
            flex: 1
        .operators
          display: flex
          align-items: center
          .icon
            flex: 1
            color: $color-theme
            &.disable
              color: $color-theme-d
            i
              font-size: 30px
          .i-left
            text-align: right
          .i-center
            padding: 0 20px
            text-align: center
            i
              font-size: 40px
          .i-right
            text-align: left
          .icon-favorite
            color: $color-sub-theme
      &.normal-enter-active, &.normal-leave-active
        transition: all 0.4s
        .top, .bottom
          transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
      &.normal-enter, &.normal-leave-to
        opacity: 0
        .top
          transform: translate3d(0, -100px, 0)
        .bottom
          transform: translate3d(0, 100px, 0)
    .mini-player
      display: flex
      align-items: center
      position: fixed
      left: 0
      bottom: 0
      z-index: 180
      width: 100%
      height: 60px
      background: $color-highlight-background
      &.mini-enter-active, &.mini-leave-active
        transition: all 0.4s
      &.mini-enter, &.mini-leave-to
        opacity: 0
      .icon
        flex: 0 0 40px
        width: 40px
        padding: 0 10px 0 20px
        img
          border-radius: 50%
          &.play
            animation: rotate 10s linear infinite
          &.pause
            animation-play-state: paused
      .text
        display: flex
        flex-direction: column
        justify-content: center
        flex: 1
        line-height: 20px
        overflow: hidden
        .name
          margin-bottom: 2px
          no-wrap()
          font-size: $font-size-medium
          color: $color-text
        .desc
          no-wrap()
          font-size: $font-size-small
          color: $color-text-d
      .control
        flex: 0 0 30px
        width: 30px
        padding: 0 10px
        .icon-play-mini, .icon-pause-mini, .icon-playlist
          font-size: 30px
          color: $color-theme-d
        .icon-mini
          font-size: 32px
          position: absolute
          left: 0
          top: 0

  @keyframes rotate
    0%
      transform: rotate(0)
    100%
      transform: rotate(360deg)
</style>